#include "sIrrlichtFont.h"
#include "sIrrlichtEngine.h"

#include <irrlicht.h>

namespace sgui
{
namespace engine
{

void sIrrlichtFont::draw(const engine::sDrawContext& context, const math::sPointf& position, const std::wstring& text, Color color) const 
{
	if (m_font)
	{
		const math::sPoint<s32>& pos = position.to<s32>() + context.getRect().getPosition().to<s32>();

		const irr::core::rect<s32> clip = m_engine.toRect<s32>(context.getRect().to<s32>());

		m_font->draw(text.c_str(), 
			m_engine.toRect<s32>(math::sRect<s32>(
				pos, math::sPoint<s32>(0, 0))
			), 
			color,
			false,
			false,
			&clip);
	}
}
	
void sIrrlichtFont::update(const preset::sPreset& preset)
{
	//
}

math::sPointf sIrrlichtFont::getSize(const std::wstring& text) const
{
	if (m_font)
	{
		irr::core::dimension2di d = m_font->getDimension(text.c_str());
		return math::sPointf((float)d.Width, (float)d.Height);
	}
	return math::sPointf(0, 0);
}
	
sIrrlichtFont::sIrrlichtFont(sIrrlichtEngine& engine, const res::sFontResource& res, const preset::sFontPreset& preset) :
	sFont(engine, res, preset), m_engine(engine), m_font(NULL), m_preset(preset)
{
	if (!res.getContents().empty())
	{
		const sgui::res::sResourceContent* cnt = res.getContents()[0];
		if (cnt)
		{
			const u32 file_size = cnt->getFileName().size();
			char* tmpdata = new char[file_size + 1];
			tmpdata[file_size] = 0;
			wcstombs(tmpdata, cnt->getFileName().c_str(), file_size);

			irr::io::IReadFile *file = engine.getDevice().getFileSystem()->
				createMemoryReadFile(cnt->getData(), cnt->getDataSize(), tmpdata);

			delete[] tmpdata;

			if (file)
			{
				irr::core::map<irr::core::stringc, irr::io::IReadFile*> files;

				for (u32 i = 1, t = res.getContents().size(); i < t; ++i)
				{
					const sgui::res::sResourceContent* rcnt = res.getContents()[i];

					const u32 file_size = rcnt->getFileName().size();
					char* rtmpdata = new char[file_size + 1];
					rtmpdata[file_size] = 0;
					wcstombs(rtmpdata, rcnt->getFileName().c_str(), file_size);
					
					irr::io::IReadFile *rfile = engine.getDevice().getFileSystem()->
						createMemoryReadFile(rcnt->getData(), rcnt->getDataSize(), rtmpdata);

					files[irr::core::stringc(rtmpdata)] = rfile;

					delete[] rtmpdata;

				}

				engine.getDriver().setTextureCreationFlag(irr::video::ETCF_NO_ALPHA_CHANNEL, false);

                m_font = engine.getDevice().getGUIEnvironment()->getFont(file, files);

				file->drop();
			}
		}
	}
}

};
};